package ui;

import dao.StudentScholarshipDao;
import model.StudentScholarship;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

/**
 * 奖学金查看面板（用于学生或教师查看所有奖学金信息）
 */
public class ScholarshipViewPanel extends JPanel {

    private final JTable scholarshipTable;       // 奖学金数据表格
    private final DefaultTableModel tableModel;  // 表格数据模型
    private JTextField searchField;              // 搜索输入框

    public ScholarshipViewPanel() {
        setLayout(new BorderLayout());

        // ===== 顶部：标题 =====
        JLabel title = new JLabel("奖学金查看", JLabel.CENTER);
        title.setFont(new Font("微软雅黑", Font.BOLD, 24));
        title.setForeground(new Color(255, 105, 180));
        add(title, BorderLayout.NORTH);

        // ===== 底部：搜索栏 =====
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        searchPanel.add(new JLabel("搜索奖学金:"));
        searchField = new JTextField(20);
        searchPanel.add(searchField);
        JButton btnSearch = new JButton("搜索");
        searchPanel.add(btnSearch);
        add(searchPanel, BorderLayout.SOUTH);

        // ===== 中部：表格展示 =====
        String[] columns = {"ID", "奖学金名称", "申报要求"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格内容不可编辑
            }
        };

        scholarshipTable = new JTable(tableModel);
        scholarshipTable.setRowHeight(60); // 每行高度适配多行文本

        // “申报要求”列使用自定义文本区域渲染器，实现多行换行显示
        scholarshipTable.getColumnModel().getColumn(2).setCellRenderer(new TextAreaRenderer());

        // 隐藏 ID 列（用于内部逻辑，用户无需看到）
        scholarshipTable.getColumnModel().getColumn(0).setMinWidth(0);
        scholarshipTable.getColumnModel().getColumn(0).setMaxWidth(0);
        scholarshipTable.getColumnModel().getColumn(0).setWidth(0);

        JScrollPane tableScroll = new JScrollPane(scholarshipTable);
        add(tableScroll, BorderLayout.CENTER);

        // ===== 初始化数据加载 =====
        loadScholarships();

        // 搜索按钮点击事件处理
        btnSearch.addActionListener(e -> searchScholarships());
    }

    /**
     * 加载所有奖学金信息到表格中
     */
    private void loadScholarships() {
        List<StudentScholarship> list = new StudentScholarshipDao().getAll();
        tableModel.setRowCount(0); // 清空旧数据
        for (StudentScholarship s : list) {
            tableModel.addRow(new Object[]{s.getId(), s.getName(), s.getCriteria()});
        }
    }

    /**
     * 根据搜索框输入的关键字过滤奖学金（按名称匹配）
     */
    private void searchScholarships() {
        String keyword = searchField.getText().trim().toLowerCase();
        List<StudentScholarship> list = new StudentScholarshipDao().getAll();
        tableModel.setRowCount(0); // 清空旧数据
        for (StudentScholarship s : list) {
            if (s.getName().toLowerCase().contains(keyword)) {
                tableModel.addRow(new Object[]{s.getId(), s.getName(), s.getCriteria()});
            }
        }
    }

    /**
     * 表格中用于支持“多行自动换行”的渲染器类
     */
    static class TextAreaRenderer extends JTextArea implements javax.swing.table.TableCellRenderer {
        public TextAreaRenderer() {
            setLineWrap(true);      // 自动换行
            setWrapStyleWord(true); // 单词边界换行
            setOpaque(true);        // 设置背景不透明
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                       boolean hasFocus, int row, int column) {
            setText(value == null ? "" : value.toString());
            int width = table.getColumnModel().getColumn(column).getWidth();
            setSize(width, Short.MAX_VALUE);
            int preferredHeight = getPreferredSize().height;
            if (table.getRowHeight(row) != preferredHeight) {
                table.setRowHeight(row, preferredHeight); // 动态调整行高
            }
            // 设置选中背景色
            setBackground(isSelected ? new Color(255, 182, 193) : Color.WHITE);
            setForeground(Color.BLACK);
            return this;
        }
    }

    /**
     * 公开方法：刷新奖学金数据
     */
    public void refreshScholarships() {
        loadScholarships();
    }

    /**
     * 提供表格访问接口（供外部获取选中行的奖学金 ID 等信息）
     */
    public JTable getTable() {
        return scholarshipTable;
    }
}
